<template>
  <div>
    <el-card style="width:70%">
      <el-form :model="user" label-width="80px" style="padding-right: 10px" :rules="rules" ref="passwordRef">
        <el-form-item label="原始密码" prop="password" >
          <el-input show-password v-model="user.password"  placeholder="请输入原始密码"></el-input>
        </el-form-item>
        <el-form-item label="修改密码" prop="newPassword" >
          <el-input show-password v-model="user.newPassword"  placeholder="请输入修改后的密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword" >
          <el-input show-password v-model="user.confirmPassword"  placeholder="请确认修改密码"></el-input>
        </el-form-item>

        <div style="text-align: center;margin-bottom: 20px">
          <el-button type="primary" @click="update">确认修改</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "Password",
  data(){
    const nextPassword= (rule, value, callback)=>{
      if(value === ''){
        callback(new Error('请输入确认密码'))
      }else if(value !== this.user.newPassword){
        callback(new Error('确认密码输入不正确'));
      }else {
        callback()
      }
    }
    return{
      user:JSON.parse(localStorage.getItem('user') || '{}'),
      rules: {
        password: [{ required: true, message: '请输入原始密码', trigger: 'blur' }],
        newPassword:[{ required: true, message: '请输入修改后的密码', trigger: 'blur' }],
        confirmPassword:[{ validator: nextPassword, required:true,trigger: 'blur' }]
      }
    }
  },
  methods:{

    update(){
      this.$refs["passwordRef"].validate((valid)=>{
        if (valid){
          this.user.password=this.user.newPassword
          this.$request.post('/user/update',this.user).then(res=>{
            if (res.code==='200'){
              this.$message.success('保存数据成功')
              this.$router.push("/login")
              localStorage.setItem("user","{}")
            }else {
              this.$message.error(res.msg)
            }
          })
        }

      })
    }
  }
}
</script>

<style scoped>

</style>